package com.shujia.hbase.api;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

public class Demo4HbaseToHdfs {
    /**
     * 基于hbase统计每个班级学生的人数
     */

    //读取hbase里面的数据

    public static class HbaseToHdfsMap extends TableMapper<Text, LongWritable> {

        @Override
        protected void map(ImmutableBytesWritable key, Result value, Mapper<ImmutableBytesWritable, Result, Text, LongWritable>.Context context) throws IOException, InterruptedException {

            String rowkey = Bytes.toString(key.get());

            byte[] clazzByte = value.getValue("info".getBytes(), "clazz".getBytes());

            String clazz = Bytes.toString(clazzByte);


            context.write(new Text(clazz), new LongWritable(1));
        }
    }

    public static class HbaseToHdfsReduce extends Reducer<Text, LongWritable, Text, NullWritable> {

        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {


            //统计班级人数
            long sum = 0;
            for (LongWritable value : values) {
                sum = sum + value.get();
            }

            String clazz = key.toString();


            String line = clazz + "," + sum;


            //将数据写入hdfs
            context.write(new Text(line), NullWritable.get());

        }
    }


    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();

        //指定zk连接地址
        conf.set("hbase.zookeeper.quorum", "node1:2181,node2:2181.node3:2181");

        Job job = Job.getInstance(conf);

        job.setJobName("HbaseToHdfs");
        job.setJarByClass(Demo4HbaseToHdfs.class);


        /**
         * 指定map端
         *
         */

        //可以指定过滤器
        Scan scan = new Scan();

        //可以增加过滤器

        scan.addFamily("info".getBytes());

        TableMapReduceUtil.initTableMapperJob("student", scan, HbaseToHdfsMap.class, Text.class, LongWritable.class, job);


        //指定reduce

        job.setReducerClass(HbaseToHdfsReduce.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);

        TextOutputFormat.setOutputPath(job, new Path("/data/clazz_num"));


        job.waitForCompletion(true);


    }

}
